package com.zpc.myvideoserver.common.security.jwt;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zpc.myvideoserver.common.security.service.UserDetailServiceImpl;
import com.zpc.myvideoserver.common.security.util.JwtUtil;
import com.zpc.myvideoserver.entity.User;
import com.zpc.myvideoserver.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName : JwtAuthenticationFilter  //类名
 * @Description : Jwt过滤器,1.携带token则验证是否过期 2.未携带则放行  //描述
 * @Author : zpc20 //作者
 * @Date: 2023/11/1  23:14
 */
// 继承基础过滤类
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    // 注入jwt工具类
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserDetailServiceImpl userDerailService;
    @Autowired
    UserService userService;
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtil.getHeader());
        System.out.println(jwt);
        if (StringUtils.isBlank(jwt)) {
            chain.doFilter(request, response);
            // 如果jwt为空直接返回
            return;
        }
        // 截取token中的有效信息
        jwt = jwt.replace("Bearer "+jwtUtil.getPrefix(),"");
        Claims claims = jwtUtil.getClaimsByToken(jwt);
        if (claims == null) {
            throw new JwtException("token异常");
        }
        if (jwtUtil.isTokenExpired(claims))
        {
            throw new JwtException("token 过期");
        }
        // 获取用户名
        String username = claims.getSubject();
        // 获取用户信息
        User user = userService.getUserByName(username);

        // 构建token 交给security进行下一步过滤
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getName(),null, AuthorityUtils.commaSeparatedStringToAuthorityList(user.getAuthorities()));
        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request,response);
    }
}
